//
//  ZCWebViewController.m
//  BaiSi
//
//  Created by 张灿 on 16/5/1.
//  Copyright © 2016年 张灿. All rights reserved.
//

#import "ZCWebViewController.h"
#import <WebKit/WebKit.h>

@interface ZCWebViewController ()
@property (weak, nonatomic) IBOutlet UIView *contentView;
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;

@property (weak, nonatomic) WKWebView *webView;


@end

@implementation ZCWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //创建网页view 并设置尺寸
    WKWebView *webView = [[WKWebView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    webView.height -= 44;
    //赋值给属性
    _webView = webView;
    
    //添加到contentview
    [self.contentView addSubview:webView];
    
    //创建请求
    NSURLRequest *request = [NSURLRequest requestWithURL:_url];
    
    //根据请求打开网页
    [webView loadRequest:request];
    
    //监听网页加载进度 KVO
    [webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    //监听网页标题
    [webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    
}

//KVO一定要记得移除!!!
- (void)dealloc
{
    [_webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [_webView removeObserver:self forKeyPath:@"title"];
    
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    //进度条赋值
    _progressView.progress = _webView.estimatedProgress;
    //进度条加载完隐藏
    _progressView.hidden = _webView.estimatedProgress >= 1;
    //标题赋值
    self.title = _webView.title;
}


- (IBAction)backClick:(id)sender {
    [_webView goBack];
}
- (IBAction)forwardClick:(id)sender {
    [_webView goForward];
}

- (IBAction)refreshClick:(id)sender {
    [_webView reload];
}

@end
